package cn.xhjava.crm.workbench.controller;

import cn.xhjava.crm.commons.ReturnObject;
import cn.xhjava.crm.commons.SysContants;
import cn.xhjava.crm.commons.util.DateUtils;
import cn.xhjava.crm.commons.util.ExceptionUtil;
import cn.xhjava.crm.commons.util.UUIDUtils;
import cn.xhjava.crm.settings.domain.DicValue;
import cn.xhjava.crm.settings.domain.User;
import cn.xhjava.crm.settings.service.DicValueService;
import cn.xhjava.crm.settings.service.UserService;
import cn.xhjava.crm.workbench.domain.*;
import cn.xhjava.crm.workbench.service.ActivityService;
import cn.xhjava.crm.workbench.service.ClueRemarkService;
import cn.xhjava.crm.workbench.service.ClueService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Author:   XiaHu
 * Date:     2023/6/27
 * 线索（潜在客户）
 */
@Controller
public class ClueController {
    private static final Logger log = LoggerFactory.getLogger(ClueController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private DicValueService dicValueService;

    @Autowired
    private ClueService clueService;

    @Autowired
    private ClueRemarkService clueRemarkService;

    @Autowired
    private ActivityService activityService;

    @RequestMapping("/workbench/clue/index")
    public String index(HttpServletRequest request) {
        log.info("跳转到 clue index");
        //调用service层方法，查询动态数据
        List<User> userList = null;
        List<DicValue> appellationList = null;
        List<DicValue> clueStateList = null;
        List<DicValue> sourceList = null;
        try {
            userList = userService.queryAllUsers();
            appellationList = dicValueService.queryDicValueByTypeCode("appellation");
            clueStateList = dicValueService.queryDicValueByTypeCode("clueState");
            sourceList = dicValueService.queryDicValueByTypeCode("source");
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //把数据保存到request中
        request.setAttribute("userList", userList);
        request.setAttribute("appellationList", appellationList);
        request.setAttribute("clueStateList", clueStateList);
        request.setAttribute("sourceList", sourceList);
        //请求转发
        return "workbench/clue/index";
    }

    @RequestMapping("/workbench/clue/queryClueForPage")
    public @ResponseBody
    Object selectForPage(String clueName,
                         String clueCompany,
                         String clueCompanyPhone,
                         String clueSource,
                         String cluePhone,
                         String clueOwner,
                         String clueState,
                         int pageNo, int pageSize, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("clueName", clueName);
        map.put("clueCompany", clueCompany);
        map.put("clueCompanyPhone", clueCompanyPhone);
        map.put("clueSource", clueSource);
        map.put("cluePhone", cluePhone);
        map.put("clueOwner", clueOwner);
        map.put("clueState", clueState);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);
        map.put("userId", user.getId());
        //调用service层方法，查询数据
        List<Clue> clueList = null;
        int totalRows = 0;
        try {
            clueList = clueService.selectForPage(map);
            totalRows = clueService.selectCountForPage(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }

        //根据查询结果结果，生成响应信息
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("clueList", clueList);
        retMap.put("totalRows", totalRows);
        return retMap;
    }


    @RequestMapping("/workbench/clue/add")
    public @ResponseBody
    Object add(Clue clue, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        clue.setId(UUIDUtils.getUUID());
        clue.setCreateTime(DateUtils.formateDateTime(new Date()));
        clue.setCreateBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，保存创建的线索
            int ret = clueService.add(clue);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("添加成功");
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }

        return returnObject;
    }

    @RequestMapping("/workbench/clue/detail")
    public String detail(String id, HttpServletRequest request) {
        Clue clue = null;
        List<ClueRemark> remarkList = null;
        List<Activity> activityList = null;
        try {
            clue = clueService.selectDetailById(id);
            remarkList = clueRemarkService.selectClueRemarkByClueId(id);
            activityList = activityService.selectClueActivityRelationByClueId(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        request.setAttribute("clue", clue);
        request.setAttribute("remarkList", remarkList);
        request.setAttribute("activityList", activityList);
        //请求转发
        return "workbench/clue/detail";
    }

    // 查询
    @RequestMapping("/workbench/clue/queryClueById")
    public @ResponseBody
    Object selectById(String id) {
        //调用service层方法，查询市场活动
        Clue clue = null;
        try {
            clue = clueService.queryClueById(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //根据查询结果，返回响应信息
        return clue;
    }


    // 修改
    @RequestMapping("/workbench/clue/update")
    public @ResponseBody
    Object update(Clue clue, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        clue.setEditTime(DateUtils.formateDateTime(new Date()));
        clue.setEditBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，保存修改的市场活动
            int ret = clueService.update(clue);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }

        return returnObject;
    }

    // 删除
    @RequestMapping("/workbench/clue/delete")
    public @ResponseBody
    Object delete(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，删除市场活动
            int ret = clueService.delete(id);
            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }


    @RequestMapping("/workbench/clue/toConvert")
    public String toConvert(String id, HttpServletRequest request) {
        //调用service层方法，查询线索的明细信息
        Clue clue = null;
        try {
            clue = clueService.selectDetailById(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        List<DicValue> stageList = null;
        try {
            stageList = dicValueService.queryDicValueByTypeCode("stage");
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        request.setAttribute("clue", clue);
        request.setAttribute("stageList", stageList);
        //请求转发
        return "workbench/clue/convert";
    }


    /**
     * 将线索数据转化为联系人、客户等数据
     * 线索转换:
     * 把线索中有关公司的信息转换到t_customer
     * 把线索中有关个人的信息转换到t_contacts
     * 把线索的备注信息转换到t_customer_remark
     * 把线索的备注信息转换到t_contacts_remark
     * 把线索和市场活动的关联关系转换到t_contacts_activity_relation
     *
     * @return
     */
    @RequestMapping("/workbench/clue/convertClue")
    public @ResponseBody
    Object convertClue(String clueId, String money, String name, String expectedDate, String stage, String activityId, String isCreateTran, HttpSession session) {
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("clueId", clueId);
        map.put("money", money);
        map.put("name", name);
        map.put("expectedDate", expectedDate);
        map.put("stage", stage);
        map.put("activityId", activityId);
        map.put("isCreateTran", isCreateTran);
        map.put(SysContants.SESSION_USER, session.getAttribute(SysContants.SESSION_USER));

        ReturnObject returnObject = new ReturnObject();
        try {
            clueService.saveConvertClue(map);
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }

        return returnObject;
    }
}
